<!-- 证书申请 -->
<template>
    <Progress :status="status" :list="list" :title="title"></Progress>
    <!-- 证书申请 -->
    <div>
        <el-form :rules="rules" v-show="status == 0" :model="certificateParam" ref="ruleFormRef"  label-width="auto" style="max-width: 600px;margin: 0 auto;">
            <el-form-item label="申请项目：" prop="projectId">
                <el-select v-model="certificateParam.projectId" placeholder="请选择申请项目" @change="findLevelList" size="large">
                    <el-option v-for="item in projectList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="证书等级：" prop="levelId">
                <el-select v-model="certificateParam.levelId" placeholder="请选择证书等级" @change="findLevelName" size="large">
                    <el-option v-for="item in levelList" :key="item.id" :label="item.name" :value="item.id"></el-option>

                </el-select>
            </el-form-item>
            <el-form-item label="申请证书：" prop="certificateIds">
                <el-select v-model="certificateParam.certificateIds" multiple placeholder="请选择申请证书" size="large">
                    <el-option v-for="item in certificateList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="上传证明：" prop="fileList"> 
                <el-upload class="upload-demo"  :on-success="fileSuccess"
                :before-upload="beforeAvatarUpload1"  :headers="headers" :limit="1"  v-model:file-list="fileList"
                :action="fileUploadAction"
                     >
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">
                        <em>需要上传本人身份证正反面+最高学历证明(扫描件或拍照)</em>
                    </div>
                    <template #tip>
                        <div class="el-upload__tip">
                            附件请打包上传，仅支持rar、zip压缩包10M以内
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item label="上传照片：" prop="avatarImage">
                <el-upload
    class="avatar-uploader"
    :headers="headers"
    :action="imageUploadAction"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    <div class="el-upload__text">
                        
                    </div> 
                    
  </el-upload>
 
                        <div class="el-upload__tip">
                            需上传本人近期2寸正面免冠照片， <br/>
                            要求：199*144像素（高*宽），2M以内，jpg格式，红色背景。                   
                        </div> 
                </el-form-item>
            <el-form-item>
                <div class="btn_all">

                    <el-button class="btn_step" type="primary" @click="onSubmit(ruleFormRef)">下一步</el-button>
                </div>
                
                </el-form-item>
        </el-form>
         <!-- 信息确认 -->
    <div v-show="status == 1">
        <PersonalInfo></PersonalInfo>
        <h3>考试信息</h3>

        <!-- <el-table class="ksboxsrc" :data="courseArray" border style="width: 100%">
            <el-table-column prop="projectName" label="考试项目" align="center" />
            <el-table-column prop="courseDate" label="考试时间" align="center" />
            <el-table-column prop="city" label="考试地点" align="center" />
            <el-table-column prop="name" label="考试模块" align="center" />
        </el-table> -->

        <div class="ksboxsrc">
            <table>
                <tbody>
                    <tr>
                        <th>申请项目</th>
                        <th>证书等级</th>
                        <th>申请证书</th>
                        <th>证书费用</th>
                    </tr>
                    <tr v-for="item in certificateData" v-bind:key="item.id">
                        <td v-text="item.projectName" style="width: 160px;"></td>
                        <td v-text="levelName"></td>
                        <td v-text="item.name"></td>
                        <td v-text="item.amount"></td>
                    </tr>
                </tbody>
            </table>
        </div>
        <form method="post">
            <h6>
                <input type="checkbox" :checked="isChecked" data-val="true" id="IsCheck" name="IsCheck" value="true">
                已阅读，遵守并同意签署<a href="">《IFFA职业道德准则》</a>
            </h6>
            <!-- 下一步按钮 -->
            <div class="btn_all" data-popname="1">
                 <el-button class="btn_step" type="primary" @click="preStep">上一步</el-button>

                <el-button class="btn_step" type="primary" @click="nextStep">下一步</el-button>

             </div>
        </form>
    </div>
 <!-- 缴费信息 -->
 <div v-show="status == 2">
        <h3>费用缴纳</h3>
        <CertificatePay :examParam="certificateParam" @paySuccess="paySuccess" ref="childPay"></CertificatePay>
        <div class="btn_all" data-popname="1">
            <el-button class="btn_step" type="primary" @click="prePayStep">上一步</el-button>
            <el-button class="btn_step" type="primary" @click="pay">确认支付</el-button>

         
        </div>
    </div>


    </div>
     <!-- 完成-->
     <div v-show="status == 3">
        <el-result
        icon="success"
        title="支付成功"
        
      >
         
      </el-result>
    </div>
</template>
<script setup lang="ts">
import { UploadFilled } from '@element-plus/icons-vue'
import { FormRules, FormInstance } from "element-plus";
const ruleFormRef = ref<FormInstance>();
import type { UploadProps,UploadUserFile,UploadFile,UploadFiles } from 'element-plus'
import store from '@/store' 
import type {CertificateParam,LevelModel,ProjectModel,CertificateModel,CertificateItemModel} from '@/api/person/exam'
import { projectListApi, levelListApi,certificateApi,certificateItemApi} from '@/api/person/exam' 
const status = ref<number>(0)
const list = ref(["证书申请", "信息确认", "缴纳费用", "完成申请"]);
const title = ref<string>('证书申请')
const certificateParam=ref<CertificateParam>({projectId:'',levelId:'',certificateIds:[],avatarImage:'',fileList:[],payType:'',amount:''})
const imageUploadAction=ref<string>(process.env.VUE_APP_BASE_URL+'upload/oss_file')
const fileUploadAction=ref<string>(process.env.VUE_APP_BASE_URL+'exam/uploadZip')
const isChecked=ref(true)
const headers=ref({
    Authorization:   store.getters.getToken
})
const rules = reactive<FormRules<CertificateParam>>({
    projectId: [
        { required: true, message: '请选择申请项目', trigger: 'change' },
    ],
    levelId: [
        { required: true, message: '请选择申请等级', trigger: 'change' },
    ],
    certificateIds: [
        { required: true, message: '请选择证书', trigger: 'change' },
    ],
    fileList: [
        { required: true, message: '请上传文件', trigger: 'change' },
    ],
     avatarImage: [
        { required: true, message: '请上传图片', trigger: 'change' },
    ],
})

const levelList = ref<LevelModel[]>([]) 
const projectList = ref<ProjectModel[]>([])
 onMounted(async () => {
    const response = await projectListApi()
    if (response.code === 200) {
        projectList.value = response.data ?? []
    } else {
        ElMessage.error(response.msg)
    }
})

const certificateList=ref<CertificateModel[]>([])
const levelName=ref<string>('')
function findLevelName(){
    levelList.value.forEach((item:any)=>{
        if(item.id===certificateParam.value.levelId){
            levelName.value=item.name
        }
    })
}
async function findLevelList() {
    levelList.value = [] 
    certificateParam.value.levelId='' 
    certificateParam.value.certificateIds=[]
    const res = await levelListApi(certificateParam.value.projectId)
    if (res.code === 200) {
        levelList.value = res.data ?? []
    } else {
        ElMessage.error(res.msg)
    }

   const response= await certificateApi(certificateParam.value.projectId)
   if (response.code === 200) {
      certificateList.value = response.data ?? []
    } else {
        ElMessage.error(response.msg)
    }
}

async function onSubmit(formEl: FormInstance | undefined) {
    if (!formEl) return;
    await formEl.validate(async (valid, fields) => {
        if (valid) { 
             
            const res= await certificateItemApi(certificateParam.value)
            if(res.code===200){
                status.value=1
                certificateData.value=res.data as CertificateItemModel[]
            }else{
                ElMessage.error(res.msg)
            }
        } else {
            console.log("error submit!", fields);
        }
    });
}
const fileList = ref<UploadUserFile[]>([ ])
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  if(response.code===200){
    certificateParam.value.avatarImage=response.data
  }
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('只限制上传jpg格式的图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('上传的图片2m以内!')
    return false
  }
  return true
}

function fileSuccess(response: any, uploadFile: UploadFile, uploadFiles: UploadFiles ){
    console.log(response, 'response')
    if(response.code===200){
        certificateParam.value.fileList=response.data
    }
    console.log(uploadFile, 'uploadFile')
    console.log(uploadFiles, 'uploadFiles')

}
const beforeAvatarUpload1: UploadProps['beforeUpload'] = (rawFile) => {
    console.log(rawFile,'rawFile')
  if (rawFile.type !== 'application/zip') {
    ElMessage.error('仅支持rar、zip压缩包')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('上传的附件文件10m以内')
    return false
  }
  return true
}
 
const imageUrl=ref('')

const certificateData=ref<CertificateItemModel[]>([{projectName:'',levelName:'',name:'' ,amount:'',id:''}])
function preStep(){
   status.value=0
}
function nextStep(){
 let sum=0
 for (let i = 0; i < certificateData.value.length; i++) {
     sum+=Number(certificateData.value[i].amount)
 } 
 certificateParam.value.amount=sum  
 status.value=2
}

function paySuccess() {
    status.value = 3
}
function prePayStep(){
    status.value=1
}
const childPay = ref<any>()

function pay(){
    childPay.value?.payType(certificateParam.value)
    status.value = 3
}

</script>
<style scoped lang='less'>
.btn_all {
    display: -webkit-box;
    display: -webkit-flex;
    display: -moz-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-justify-content: center;
    -moz-justify-content: center;
    -ms-justify-content: center;
    -o-justify-content: center;
    justify-content: center;
    max-width: 500px;
    margin: 0 auto;
}

.btn_step {
    margin: 20px 10px 0;
    display: block;
    width: 213px;
    height: 48px;
    font-size: 16px;
    color: #fff;
    text-align: center;
    margin: 30px auto 0;
    background-color: #345aa3;
    cursor: pointer;
}

:deep(.upload-demo) {
    width: 100%;
}
.avatar-uploader{
    border: 1px dashed var(--el-border-color);

}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}


.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.ksboxsrc {
    overflow: hidden;
    overflow-x: auto;
}

.ksboxsrc table {
    width: 100%;
    width: 539px;
    margin: 0 auto;
}

table {
    border-collapse: collapse;
    border-spacing: 0;
}

.ksboxsrc table tr th {
    font-size: 18px;
    line-height: 48px;
    text-align: center;
    color: #ffffff;
    background-color: #345aa3;
    border-right: 1px solid #fff;
    border-bottom: 1px solid #fff;
}

.ksboxsrc table tr th {
    font-size: 18px;
    line-height: 48px;
    text-align: center;
    color: #ffffff;
    background-color: #345aa3;
    border-right: 1px solid #fff;
    border-bottom: 1px solid #fff;
}

.ksboxsrc table tr td:nth-of-type(1),
.ksboxsrc table tr td:nth-of-type(3) {
    width: 129px;
}

.ksboxsrc table tr td {
    font-size: 14px;
    line-height: 40px;
    text-align: center;
    color: #444444;
    background-color: rgba(238, 238, 238, 0.5);
    border-right: 1px solid #fff;
    border-bottom: 1px solid #fff;
}
.btn_all {
    display: -webkit-box;
    display: -webkit-flex;
    display: -moz-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-justify-content: center;
    -moz-justify-content: center;
    -ms-justify-content: center;
    -o-justify-content: center;
    justify-content: center;
    max-width: 500px;
    margin: 0 auto;
}

 
</style>